package tr.gov.tubitak.uekae.esya.api.cades.example.sign;

import junit.framework.TestCase;
import tr.gov.tubitak.uekae.esya.api.asn.x509.ECertificate;
import tr.gov.tubitak.uekae.esya.api.cades.example.testconstans.TestConstants;
import tr.gov.tubitak.uekae.esya.api.cades.example.validation.ValidationUtil;
import tr.gov.tubitak.uekae.esya.api.cmssignature.ISignable;
import tr.gov.tubitak.uekae.esya.api.cmssignature.SignableByteArray;
import tr.gov.tubitak.uekae.esya.api.cmssignature.attribute.EParameters;
import tr.gov.tubitak.uekae.esya.api.cmssignature.signature.BaseSignedData;
import tr.gov.tubitak.uekae.esya.api.cmssignature.signature.ESignatureType;
import tr.gov.tubitak.uekae.esya.api.cmssignature.validation.SignedDataValidationResult;
import tr.gov.tubitak.uekae.esya.api.cmssignature.validation.SignedData_Status;
import tr.gov.tubitak.uekae.esya.api.common.crypto.BaseSigner;
import tr.gov.tubitak.uekae.esya.api.infra.tsclient.TSSettings;
import tr.gov.tubitak.uekae.esya.api.smartcard.example.SmartCardManager;
import tr.gov.tubitak.uekae.esya.asn.util.AsnIO;

import java.util.HashMap;

public class ESTSign extends TestCase 
{
	/**
	 * creates EST type signature and validate it.
	 * @throws Exception
	 */
	public void testEstSign() throws Exception
	{
		BaseSignedData bs = new BaseSignedData();
		
		ISignable content = new SignableByteArray("test".getBytes());
		bs.addContent(content);
		
		HashMap<String, Object> params = new HashMap<String, Object>();
		
		//if the user does not want certificate validation,he can add 
		//P_VALIDATE_CERTIFICATE_BEFORE_SIGNING parameter with its value set to false
		
		//if the user want to do timestamp validation while generating signature,he can add
		//P_VALIDATE_TIMESTAMP_WHILE_SIGNING parameter with its value set to true
		//params.put(EParameters.P_VALIDATE_TIMESTAMP_WHILE_SIGNING, true);	
		boolean checkQCStatement = TestConstants.getCheckQCStatement();
		params.put(EParameters.P_CERT_VALIDATION_POLICY, TestConstants.getPolicy());
		
		//necessary for getting signature time stamp.
		TSSettings tsSettings = TestConstants.getTSSettings();
		params.put(EParameters.P_TSS_INFO, tsSettings);
		
		
		//Get qualified or non-qualified certificate.
		ECertificate cert = SmartCardManager.getInstance().getSignatureCertificate(checkQCStatement, !checkQCStatement);
		BaseSigner signer = SmartCardManager.getInstance().getSigner(TestConstants.getPIN(), cert);
		
		//add signer
		bs.addSigner(ESignatureType.TYPE_EST, cert, signer, null, params);
		
		SmartCardManager.getInstance().logout();
		
		byte [] signedDocument = bs.getEncoded();
		
		AsnIO.dosyayaz(signedDocument,TestConstants.getDirectory() + "testdata/EST-1.p7s");
		
		SignedDataValidationResult sdvr = ValidationUtil.validate(signedDocument, null);
		
		assertEquals(SignedData_Status.ALL_VALID, sdvr.getSDStatus());
	}
}
